package response

import (
	"carSpider/data"
	"fmt"
	goSpider "github.com/Flyits/goSpider/src"
	"github.com/antchfx/htmlquery"
	"strings"
)

func Version(response goSpider.Response, spider *goSpider.Spider) {
	modelAttachData(response)

	versionList := htmlquery.Find(response.HtmlNode, "//div[@class='car-year-style-list']/div")
	var version data.Version
	version.BrandId = response.Attach.(map[string]int)["brandId"]
	version.BrandModelId = response.Attach.(map[string]int)["modelId"]
	version.Images = "{}"
	version.ParamConfig = "{}"
	for k, _ := range versionList {
		className := htmlquery.SelectAttr(versionList[k], "class")

		if strings.Index(className, "car-style-info") != -1 {
			version.Classify = htmlquery.FindOne(versionList[k], "./span[@class='c-style-val']/text()").Data
		}
		if strings.Index(className, "c-style-warp") != -1 {
			version.Name = strings.Trim(strings.Trim(htmlquery.FindOne(versionList[k], ".//h1/text()").Data, " "), "\n")
			version.StyleYear = htmlquery.SelectAttr(htmlquery.FindOne(versionList[k], ".//div[@class='compare-box']"), "data-year")
			configUrl := htmlquery.SelectAttr(htmlquery.FindOne(versionList[k], ".//a"), "href") + "peizhi"
			urlParams := strings.Split(strings.Trim(configUrl, "/"), "/")
			version.FirstImage = configUrl
			id := versionExists(version)
			attach := map[string]int{"brandId": version.BrandId, "modelId": version.BrandModelId, "versionId": id}
			// 若为新数据，继续向下爬取配置&图片数据
			if id > 53455 {
				//spider.AddJob(goSpider.UrlItem{
				//	Url:         BaseUrl + configUrl,
				//	HandlerFunc: Config,
				//	SpiderFunc:  goSpider.JsLoadRequest,
				//	WaitExpr:    "#content-iscoll",
				//	Expr:        "#content-iscoll",
				//	Attach:      attach,
				//})
				fmt.Println(ImgBaseUrl+strings.TrimLeft(urlParams[1], "m"), id, version)
				spider.AddJob(goSpider.UrlItem{
					Url:         ImgBaseUrl + strings.TrimLeft(urlParams[1], "m"),
					HandlerFunc: Image,
					Attach:      attach,
				})
			}
		}

	}
}

// 补充车型数据
func modelAttachData(response goSpider.Response) {
	var (
		model data.Model
	)
	priceNode := htmlquery.FindOne(response.HtmlNode, "//span[@class='car-price']/text()")
	guidPriceNode := htmlquery.FindOne(response.HtmlNode, "//div[@class='guid-price']/em[1]/text()")
	//model.SubBrandName = htmlquery.FindOne(response.HtmlNode, "//div[@class='guid-price']/span[2]/text()").Data
	if priceNode != nil && priceNode.Data != "暂无报价" && priceNode.Data != "暂无预售价" {
		model.SellingPrice = priceNode.Data + "万"
	} else {
		model.SellingPrice = "暂无报价"
	}
	if guidPriceNode != nil && (guidPriceNode.Data == "指导价" || guidPriceNode.Data == "预售价") {
		model.GuidPrice = htmlquery.FindOne(response.HtmlNode, "//div[@class='guid-price']/span[1]/text()").Data
	} else {
		model.GuidPrice = "暂无指导价"
	}

	model.BrandId = response.Attach.(map[string]int)["brandId"]
	model.ID = response.Attach.(map[string]int)["modelId"]
	if model.ID > 4535 {
		data.Db.Model(&model).Updates(map[string]interface{}{"selling_price": model.SellingPrice, "guid_price": model.GuidPrice})
	}
}

// 检测数据是否存在
func versionExists(result data.Version) int {
	var version data.Version
	data.Db.Where("name = ? and brand_id = ? and brand_model_id = ?", result.Name, result.BrandId, result.BrandModelId).First(&version)
	if data.Db.NewRecord(version) {
		data.Db.Create(&result)
		fmt.Println(result)
		return result.ID
	}
	fmt.Println(version)
	return version.ID
}
